package com.hh.usersystem.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hh.baseframework.util.Check;
import com.hh.baseframework.util.Convert;
import com.hh.baseframework.util.MessageException;
import com.hh.baseframework.util.dto.ExtTree;
import com.hh.baseframework.util.dto.PageRange;
import com.hh.hibernate.dao.inf.IHibernateDAO;
import com.hh.hibernate.util.dto.HQLParamList;
import com.hh.hibernate.util.dto.PagingData;
import com.hh.usersystem.bean.usersystem.HhXtOrgJs;
import com.hh.usersystem.bean.usersystem.HhXtYh;
import com.hh.usersystem.bean.usersystem.HhXtYhOrg;
import com.hh.usersystem.bean.usersystem.Organization;
import com.hh.usersystem.util.app.LoginUser;
import com.hh.usersystem.util.steady.StaticProperties;

@Service
public class OrganizationService {
	@Autowired
	private IHibernateDAO<Organization> dao;
	@Autowired
	private IHibernateDAO<HhXtYhOrg> hhXtYhOrgDAO;
	@Autowired
	private IHibernateDAO<HhXtYh> xtyhdao;
	@Autowired
	private IHibernateDAO<HhXtOrgJs> hhxtorgjsdao;
	@Autowired
	private LoginUserUtilService loginUserUtilService;

	public List<Organization> organizationToIconCls(
			List<Organization> organizationList) {
		for (Organization organization : organizationList) {
			if (organization != null) {
				organization.setIconCls(organization.getLx_() == 0 ? "group"
						: organization.getLx_() == 1 ? "org" : organization
								.getLx_() == 2 ? "dept"
								: organization.getLx_() == 3 ? "job" : "");
				organization.setIcon(null);
			}
		}
		return organizationList;
	}

	public PagingData<Organization> queryPagingData(Organization organization,
			PageRange pageRange) {
		return dao.queryPagingData(Organization.class, pageRange);
	}

	public List<Organization> queryOrgListByPidAndLx(Organization organization,
			String node) {
		String pid = !Check.isEmpty(node)
				&& "root".equals(organization.getNode()) ? node : organization
				.getNode();
		HQLParamList hqlParamList = new HQLParamList();
		// pid = "root".equals(pid) ? "0" : pid;
		hqlParamList.add(Restrictions.eq("node", pid));
		hqlParamList.add(Restrictions.eq("lx_", organization.getLx_()));
		// hqlParamList.add(Restrictions.eq("zt_", 0));
//		hqlParamList.add(Order.desc(StaticVar.ORDER));
		return organizationToIconCls(dao.queryList(Organization.class,
				hqlParamList));
	}

	public List<Organization> queryOrgListByPid(String node, String orgs) {
		// node = "root".equals(node) ? "0" : node;
		HQLParamList hqlParamList = new HQLParamList();
		List<Organization> organizationList = null;
		if ("root".equals(node) && Check.isNoEmpty(orgs)) {
			hqlParamList.add(Restrictions.in("id", Convert.strToList(orgs)));
			hqlParamList.add(Order.asc("lx_"));
//			hqlParamList.add(Order.desc(StaticVar.ORDER));
			organizationList = dao.queryList(Organization.class, hqlParamList);
			List<String> codeList = new ArrayList<String>();
			for (Organization organization : organizationList) {
				if (codeList.size() == 0) {
					codeList.add(organization.getCode_());
				} else {
					List<String> removeCodeList = new ArrayList<String>();
					boolean isAdd = true;
					for (String code : codeList) {
						if (code.indexOf(organization.getCode_()) > -1) {
							removeCodeList.add(code);
						} else if (organization.getCode_().indexOf(code) > -1) {
							isAdd = false;
						} else {
						}
					}
					codeList.remove(removeCodeList);
					if (isAdd) {
						codeList.add(organization.getCode_());
					}
				}
			}
			List<Organization> organizations = new ArrayList<Organization>();
			for (Organization organization : organizationList) {
				if (codeList.contains(organization.getCode_())) {
					organizations.add(organization);
				}
			}
			organizationList = organizations;
		} else {
			hqlParamList.add(Restrictions.eq("zt_", 0));
			hqlParamList.add(Restrictions.eq("node", node));
			hqlParamList.add(Order.asc("lx_"));
//			hqlParamList.add(Order.desc(StaticVar.ORDER));
			organizationList = dao.queryList(Organization.class, hqlParamList);
		}
		for (Organization organization : organizationList) {
			organization.setText(organization.getText()
					+ "<font color='red'>（"
					+ (organization.getLx_() == 0 ? "集团" : organization
							.getLx_() == 1 ? "机构"
							: organization.getLx_() == 2 ? "部门" : organization
									.getLx_() == 3 ? "岗位" : "") + "）</font>");
		}
		return organizationToIconCls(organizationList);
	}

	public Organization findObjectById(String id) {
		Organization organization = dao.findEntityByPK(Organization.class, id);
		if (organization != null) {
			Organization p_organization = dao.findEntityByPK(
					Organization.class, organization.getNode());
			if (p_organization == null) {
			} else {
				organization.setPname_(p_organization.getText());
				organization.setSjbm_(p_organization.getCode_());
				organization.setNode(p_organization.getId());
			}
			List<HhXtOrgJs> hhXtYhJsList = hhxtorgjsdao.queryList(
					HhXtOrgJs.class, new HQLParamList()
							.addCondition(Restrictions.eq("orgId", id)));
			for (HhXtOrgJs hhXtOrgJs : hhXtYhJsList) {
				organization.getJsList().add(hhXtOrgJs.getJsId());
			}
		}
		return organization;
	}

	public Organization save(Organization organization) throws MessageException {

		if (Check.isEmpty(organization.getNode())) {
			organization.setNode("root");
		}

		organization
				.setCode_(organization.getSjbm_() + organization.getCode_());
		if (checkCodeOnly(organization)) {
			throw new MessageException("编码重复，请更换！");
		}

		if (Check.isEmpty(organization.getId())) {
			organization.setId(UUID.randomUUID().toString());
			dao.createEntity(organization);
		} else {
			Organization old_organization = dao.findEntityByPK(
					Organization.class, organization.getId());
			if (organization.getId().equals(organization.getNode())) {
				throw new MessageException("不能选自己为上级！");
			}
			dao.updateEntity("update Organization o set  o.code_=  replace(o.code_,'"
					+ old_organization.getCode_()
					+ "','"
					+ organization.getCode_()
					+ "') where o.code_ like '"
					+ old_organization.getCode_()
					+ "%' and o.code_ !='"
					+ old_organization.getCode_() + "' ");

			dao.mergeEntity(organization);

			hhxtorgjsdao.deleteEntity(HhXtOrgJs.class, "orgId",
					organization.getId());
		}
		List<String> jsList = organization.getJsList();
		if (!Check.isEmpty(jsList)) {
			for (String jsid : jsList) {
				if (Check.isEmpty(jsid)) {
					continue;
				}
				HhXtOrgJs hhXtOrgJs = new HhXtOrgJs();
				hhXtOrgJs.setOrgId(organization.getId());
				hhXtOrgJs.setJsId(jsid);
				hhxtorgjsdao.createEntity(hhXtOrgJs);
			}
		}
		return organization;
	}

	private boolean checkCodeOnly(Organization organization) {
		return dao.findWhetherData("select count(o) from "
				+ organization.getClass().getName() + " o "
				+ "where o.code_=:code_ and (o.id!=:id or :id is null)",
				organization);
	}

	public void deleteByIds(String ids) {
		List<String> idList = Convert.strToList(ids);
		deleteYzNode(idList);
		if (!Check.isEmpty(idList)) {
			dao.deleteEntity(Organization.class, "id", idList);
			hhXtYhOrgDAO.deleteEntity(HhXtYhOrg.class, "orgId", idList);
			hhxtorgjsdao.deleteEntity(HhXtOrgJs.class, "orgId", idList);
		}

	}

	private void deleteYzNode(List<String> idList) {
		List<String> yzIdList = new ArrayList<String>();
		if (!Check.isEmpty(idList)) {
			List<Organization> hhxtcdList = dao.queryList(Organization.class,
					Restrictions.in("node", idList));
			for (Organization hhXtCd : hhxtcdList) {
				yzIdList.add(hhXtCd.getId());
			}
			if (!Check.isEmpty(yzIdList)) {
				dao.deleteEntity(Organization.class, "id", yzIdList);
				hhXtYhOrgDAO.deleteEntity(HhXtYhOrg.class, "orgId", yzIdList);
				hhxtorgjsdao.deleteEntity(HhXtOrgJs.class, "orgId", yzIdList);
			}
			deleteYzNode(yzIdList);

		}

	}

	public List<Object> queryOrgAndUsersList(String node) {
		List<Organization> organizations = this.queryOrgListByPid(node, null);
		List<Object> objects = new ArrayList<Object>();
		Organization organization = dao
				.findEntityByPK(Organization.class, node);
		if (Check.isNoEmpty(organization)) {
			if (organization.getLx_() == 3) {
				List<HhXtYhOrg> hhXtYhOrgs = hhXtYhOrgDAO.queryList(
						HhXtYhOrg.class, new HQLParamList()
								.addCondition(Restrictions.eq("orgId",
										organization.getId())));
				List<String> yhid = new ArrayList<String>();
				for (HhXtYhOrg hhXtYhOrg : hhXtYhOrgs) {
					yhid.add(hhXtYhOrg.getYhId());
				}
				if (!Check.isEmpty(yhid)) {
					List<HhXtYh> hhXtYhs = xtyhdao.queryList(
							HhXtYh.class,
							new HQLParamList().addCondition(
									Restrictions.in("id", yhid))
//									.addCondition(Order.desc(StaticVar.ORDER))
									);
					for (HhXtYh hhXtYh : hhXtYhs) {

						ExtTree extTree = new ExtTree();
						extTree.setId("{orgid : '" + organization.getId()
								+ "' ,userid : '" + hhXtYh.getId() + "'}");
						extTree.setText(hhXtYh.getText());
						if (LoginUser.getLoginUserId().contains(hhXtYh.getId())) {
							extTree.setIcon(hhXtYh.getNxb() == 0 ? StaticProperties.HHXT_USERSYSTEM_NV
									: StaticProperties.HHXT_USERSYSTEM_NAN);
						} else {
							extTree.setIcon(StaticProperties.HHXT_NO_ON_LINE_USER_ICON);
						}

						extTree.setLeaf(1);
						objects.add(extTree);
					}
				}
			}
		}

		if (Check.isNoEmpty(organizations)) {
			for (Organization organization2 : organizationToIconCls(organizations)) {
				objects.add(organization2);
			}
		}

		return objects;
	}

	public List<Organization> queryCurrOrgTree(String node, String action) {
		List<Organization> organizations = new ArrayList<Organization>();
		if ("root".equals(node)) {
			organizations
					.add(loginUserUtilService.queryDataSecurityOrg(action));
		} else {
			HQLParamList hqlParamList = new HQLParamList();
			hqlParamList.add(Restrictions.like("code_", node + "___"));
			organizations = dao.queryList(Organization.class, hqlParamList);
		}
		for (Organization organization : organizations) {
			if (organization != null) {
				organization.setId(organization.getCode_());
			}
		}
		return organizationToIconCls(organizations);
	}

}
